package com.xsmart.order.services.core;

import com.xsmart.common.constant.ResultConstant;
import com.xsmart.common.entity.RequestBean;
import com.xsmart.common.entity.ResponseBean;
import com.xsmart.order.dao.CartDao;
import com.xsmart.order.dao.GoodsManageDao;
import com.xsmart.order.dao.ShippingTempletDao;
import com.xsmart.order.pojo.SellerInfo;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车结算
 *
 * @author guojd
 */
@Service
public class OrderSettleService {
    @Autowired
    CartDao cartDao;
    @Autowired
    GoodsManageDao goodsManageDao;
    @Autowired
    ShippingTempletDao shippingTempletDao;

    /**
     * 购物车结算 获取数据
     *
     * @param requestBean 请求对象
     * @param cartIds     结算购物列表
     * @param uid         用户ID
     * @return 结算信息
     */
    public ResponseBean orderSettle(RequestBean requestBean, String[] cartIds, Integer uid) {
        ResponseBean responseBean = requestBean.getResponseBean();
        //商品总价
        float price = 0;
        //运费
        float shippingFee = 0;
        //商品列表
        List<Map<String, Object>> goodsList = new ArrayList<>();
        //超过库存的商品数量
        int isLack = 0;
        //订单商品成本价
        float costsPrice = 0;
        Map<Integer, SellerInfo> sellerInfoMap = new HashMap<>();
        for (String sCartId : cartIds) {
            int cartId = Integer.parseInt(sCartId);
            Map<String, Object> cartInfo = cartDao.queryCartByRecId(cartId);
            if (cartInfo == null || cartInfo.size() == 0) {
                responseBean.setResult(ResultConstant.ERROR);
                responseBean.setMessage("非法操作");
                return responseBean;
            }
            Map<String, Object> goodsInfo = goodsManageDao.queryGoodsInfo(MapUtils.getInteger(cartInfo, "goods_id"));
            if (goodsInfo == null || goodsInfo.size() == 0) {
                responseBean.setResult(ResultConstant.ERROR);
                responseBean.setMessage("非法操作");
                return responseBean;
            }
            int goodsNumber = MapUtils.getIntValue(goodsInfo, "goods_number", 0);

            Float goodsPrice = MapUtils.getFloat(goodsInfo, "goods_price");
            Float costPrice = MapUtils.getFloat(goodsInfo, "cost_price");
            Float goodsWeight = MapUtils.getFloat(goodsInfo, "goods_weight", 0f);
            int cartNum = MapUtils.getIntValue(cartInfo, "goods_number", 0);
            if (cartNum > goodsNumber) {
                goodsInfo.put("numIsLack", 1);
                goodsInfo.put("numIsLackStr", "只剩" + goodsNumber + "件");
                isLack++;
            }

            if (goodsPrice == null || cartNum == 0) {
                responseBean.setResult(ResultConstant.ERROR);
                responseBean.setMessage("非法操作");
                return responseBean;
            }
            Integer fromSellerId = MapUtils.getInteger(goodsInfo, "from_seller_id", -1);
            Float allPrice = goodsPrice * cartNum;
            Float allWeight = goodsWeight * cartNum;
            goodsInfo.put("all_price", allPrice);
            goodsInfo.put("cart_num", cartNum);
            price += goodsPrice * cartNum;
            costsPrice += costPrice * cartNum;
            goodsList.add(goodsInfo);
            getIntegerSellerInfoMap(sellerInfoMap, fromSellerId, cartNum, allPrice, allWeight);
        }
        responseBean.setResult(ResultConstant.SUCCESS);
        //是否存在商品超过库存
        if (isLack > 0) {
            responseBean.addResultItem("isLack", 1);
        } else {
            responseBean.addResultItem("isLack", 0);
        }
        price = Math.round(price * 100) / 100f;
        responseBean.addResultItem("costs_price", costsPrice);
        responseBean.addResultItem("pro", goodsList);
        responseBean.addResultItem("adds", "");
        Map<String, Object> address = (Map<String, Object>) requestBean.getRequestParam("address");
        shippingFee = getPost(sellerInfoMap, address);
        if(shippingFee==-1){
            shippingFee=0;
            responseBean.addResultItem("hasShipping", false);
        }else{
            responseBean.addResultItem("hasShipping", true);
        }

        responseBean.addResultItem("yun", shippingFee);
        responseBean.addResultItem("price", price + shippingFee);
        return responseBean;
    }

    /**
     * 立即购买结算
     *
     * @param requestBean
     * @param goodsId
     * @param uid
     * @param buyNum
     * @return
     */
    public ResponseBean orderSettle(RequestBean requestBean, Integer goodsId, Integer uid, Integer buyNum) {
        ResponseBean responseBean = requestBean.getResponseBean();
        //商品总价
        float price = 0;
        //运费
        float shippingFee = 0;
        //商品列表
        List<Map<String, Object>> goodsList = new ArrayList<>();
        //订单商品成本价
        float costsPrice = 0;
        Map<String, Object> goodsInfo = goodsManageDao.queryGoodsInfo(goodsId);
        if (goodsInfo == null || goodsInfo.size() == 0) {
            responseBean.setResult(ResultConstant.ERROR);
            responseBean.setMessage("非法操作");
            return responseBean;
        }
        int goodsNumber = MapUtils.getIntValue(goodsInfo, "goods_number", 0);
        Float goodsPrice = MapUtils.getFloat(goodsInfo, "goods_price");
        Float costPrice = MapUtils.getFloat(goodsInfo, "cost_price");
        Float goodsWeight = MapUtils.getFloat(goodsInfo, "goods_weight", 0f);
        if (buyNum > goodsNumber) {
            responseBean.setResult(ResultConstant.ERROR);
            responseBean.setMessage("库存不足，只剩" + goodsNumber + "件");
            return responseBean;
        }
        if (goodsPrice == null || buyNum == 0) {
            responseBean.setResult(ResultConstant.ERROR);
            responseBean.setMessage("非法操作");
            return responseBean;
        }
        Integer fromSellerId = MapUtils.getInteger(goodsInfo, "from_seller_id", -1);
        Float allPrice = goodsPrice * buyNum;
        Float allWeight = goodsWeight * buyNum;
        goodsInfo.put("all_price", allPrice);
        goodsInfo.put("cart_num", buyNum);
        price += goodsPrice * buyNum;
        costsPrice += costPrice * buyNum;
        goodsList.add(goodsInfo);
        responseBean.setResult(ResultConstant.SUCCESS);
        price = Math.round(price * 100) / 100f;
        responseBean.addResultItem("costs_price", costsPrice);
        responseBean.addResultItem("pro", goodsList);
        responseBean.addResultItem("adds", "");
        Map<Integer, SellerInfo> sellerInfoMap = new HashMap<>();
        getIntegerSellerInfoMap(sellerInfoMap, fromSellerId, buyNum, allPrice, allWeight);
        Map<String, Object> address = (Map<String, Object>) requestBean.getRequestParam("address");
        shippingFee = getPost(sellerInfoMap, address);
        if(shippingFee==-1){
            shippingFee=0;
            responseBean.addResultItem("hasShipping", false);
        }else{
            responseBean.addResultItem("hasShipping", true);
        }

        responseBean.addResultItem("yun", shippingFee);
        responseBean.addResultItem("price", price + shippingFee);
        return responseBean;
    }

    /**
     * 立即购买
     *
     * @param requestBean
     * @param goodsId
     * @param buyNum
     * @return
     */
    public ResponseBean buyNow(RequestBean requestBean, Integer goodsId, Integer buyNum) {
        ResponseBean responseBean = requestBean.getResponseBean();
        //商品总价
        float price = 0;
        //运费
        float shippingFee = 0;
        int isLack = 0;
        //商品列表
        List<Map<String, Object>> goodsList = new ArrayList<>();
        //
        Map<String, Object> goodsInfo = goodsManageDao.queryGoodsInfo(goodsId);
        if (goodsInfo == null || goodsInfo.size() == 0) {
            responseBean.setResult(ResultConstant.ERROR);
            responseBean.setMessage("非法操作");
            return responseBean;
        }
        int goodsNumber = MapUtils.getIntValue(goodsInfo, "goods_number", 0);
        Float goodsPrice = MapUtils.getFloat(goodsInfo, "goods_price");
        Float goodsWeight = MapUtils.getFloat(goodsInfo, "goods_weight", 0f);
        if (buyNum > goodsNumber) {
            goodsInfo.put("numIsLack", 1);
            goodsInfo.put("numIsLackStr", "只剩" + goodsNumber + "件");
            isLack++;
        }
        if (goodsPrice == null || buyNum == 0) {
            responseBean.setResult(ResultConstant.ERROR);
            responseBean.setMessage("非法操作");
            return responseBean;
        }
        Integer fromSellerId = MapUtils.getInteger(goodsInfo, "from_seller_id", -1);
        Float allPrice = goodsPrice * buyNum;
        Float allWeight = goodsWeight * buyNum;
        goodsInfo.put("all_price", allPrice);
        goodsInfo.put("cart_num", buyNum);
        price += goodsPrice * buyNum;
        goodsList.add(goodsInfo);
        responseBean.setResult(ResultConstant.SUCCESS);
        //是否存在商品超过库存
        if (isLack > 0) {
            responseBean.addResultItem("isLack", 1);
        } else {
            responseBean.addResultItem("isLack", 0);
        }
        price = Math.round(price * 100) / 100f;
        responseBean.addResultItem("pro", goodsList);
        Map<Integer, SellerInfo> sellerInfoMap = new HashMap<>();
        getIntegerSellerInfoMap(sellerInfoMap, fromSellerId, buyNum, price, allWeight);
        Map<String, Object> address = (Map<String, Object>) requestBean.getRequestParam("address");
        shippingFee = getPost(sellerInfoMap, address);
        if(shippingFee==-1){
            shippingFee=0;
            responseBean.addResultItem("hasShipping", false);
        }else{
            responseBean.addResultItem("hasShipping", true);
        }
        responseBean.addResultItem("yun", shippingFee);
        responseBean.addResultItem("price", price + shippingFee);
        return responseBean;
    }

    /**
     * 计算店铺订单信息
     *
     * @param fromSellerId 店铺id
     * @param buyNum       商品购买数量
     * @param price        价格
     * @param weight       重量
     * @return
     */
    private void getIntegerSellerInfoMap(Map<Integer, SellerInfo> sellerInfoMap, Integer fromSellerId, Integer buyNum, Float price, Float weight) {
        SellerInfo sellerInfo;
        if (sellerInfoMap.containsKey(fromSellerId)) {
            sellerInfo = sellerInfoMap.get(fromSellerId);
        } else {
            sellerInfo = new SellerInfo();
            sellerInfo.setSellerId(fromSellerId);
            sellerInfoMap.put(sellerInfo.getSellerId(), sellerInfo);
        }
        sellerInfo.addPrice(price);
        sellerInfo.addGoodsNum(buyNum);
        sellerInfo.addWeight(weight);
    }

    /**
     * 获取运费
     *
     * @param sellerInfoMap 商家
     * @return 运费
     */
    private Float getPost(Map<Integer, SellerInfo> sellerInfoMap, Map<String, Object> address) {
        Integer country = MapUtils.getInteger(address, "country", -1);
        Integer province = MapUtils.getInteger(address, "province", -1);
        Integer city = MapUtils.getInteger(address, "city", -1);
        Integer district = MapUtils.getInteger(address, "district", -1);
        if (district == -1) {
            return -1f;
        }
        Float shippingFee = 0f;
        for (Integer sellerId : sellerInfoMap.keySet()) {
            List<Map<String, Object>> shippingTempletList = shippingTempletDao.getShippingTempletBySellerId(sellerId);
            if (shippingTempletList.size() == 0) {
                shippingFee = -1f;
                break;
            } else {
                boolean hasShipping = false;
                for (Map<String, Object> shippingTemplet : shippingTempletList) {
                    String areaIds = "," + MapUtils.getString(shippingTemplet, "shipping_area_ids", "") + ",";
                    Float fee = MapUtils.getFloat(shippingTemplet, "shipping_first_fee", 0f);
                    if (areaIds.contains("," + district + ",") || areaIds.contains("," + city + ",")
                            || areaIds.contains("," + province + ",") || areaIds.contains("," + country + ",")) {
                        shippingFee += fee;
                        hasShipping = true;
                        break;
                    }
                }
                if (!hasShipping) {
                    return -1f;
                }
            }
        }
        return shippingFee;
    }
}
